<script lang="ts" setup>
import {reactive, ref} from 'vue'
import { switchNavBarTheme } from "@/utils/common";
import {onLoad, onReachBottom, onShow} from '@dcloudio/uni-app';
import type {TransactionQueryParams, TransactionRecordVO, WalletInfoVO} from "@/types/pay";
import {getTransactionRecordByPageAPI, getWalletInfoAPI} from "@/api/pay";
import {TransactionType} from "@/types/constants";
import type { LoadMoreState } from 'wot-design-uni/components/wd-loadmore/types';

const walletInfo = reactive<WalletInfoVO>({
  walletId: 0,
  balance: '0.00',
  todayIncome: '0.00',
  todayExpenditure: '0.00',
  transactionRecordVO: []
})
const yearMonth = ref<number>(Date.now())
const toYearMonth = (timestamp: number) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  return year + '-' + month
}
const transactionQueryParams = reactive<TransactionQueryParams>({
  page: 1,
  pageSize: 10,
  walletId: 0,
  yearMonth: toYearMonth(yearMonth.value)
})
const initState = <{state: LoadMoreState, isLoaded: boolean, page: number}>{ state: 'loading', isLoaded: false, page: 1 }
const listInfo = reactive<{ state: LoadMoreState, isLoaded: boolean, page: number }[]>(Array.from({ length: 3 }, () => ({ ...initState })))
onLoad(() => {
  switchNavBarTheme()
})
const current = ref(-1)
onShow(async () => {
  current.value = -1
  yearMonth.value = Date.now()
  transactionQueryParams.yearMonth = toYearMonth(yearMonth.value)
  Object.assign(listInfo, Array.from({ length: 3 }, () => ({ ...initState })))
  const res = await getWalletInfoAPI()
  if (res.code === 200) {
    Object.assign(walletInfo, res.data)
    transactionQueryParams.walletId = walletInfo.walletId
    listInfo[0].isLoaded = true
    if (walletInfo.transactionRecordVO.length < transactionQueryParams.pageSize) listInfo[0].state = 'finished'
  }
})

const show = ref(true)
const hideStr = ref("****")
const list = ref<{value: number, payload: string}[]>([
  {value: -1, payload: '全部'},
  {value: 0, payload: '收入'},
  {value: 1, payload: '支出'}
])

const incomeRecord = reactive<TransactionRecordVO[]>([])
const expenditureRecord = reactive<TransactionRecordVO[]>([])
const changeList = async () => {
  if (!listInfo[current.value + 1].isLoaded) {
    if (current.value === -1) delete transactionQueryParams.transactionType
    else transactionQueryParams.transactionType = current.value
    const res = await getTransactionRecordByPageAPI(transactionQueryParams)
    if (res.code === 200) {
      listInfo[current.value + 1].isLoaded = true
      if (res.data.length < transactionQueryParams.pageSize) listInfo[current.value + 1].state = 'finished'
      if (current.value === -1) Object.assign(walletInfo.transactionRecordVO, res.data)
      else if (current.value === 0) Object.assign(incomeRecord, res.data)
      else Object.assign(expenditureRecord, res.data)
    }
  }
}

const changeDate = () => {
  const oldYearMonth = transactionQueryParams.yearMonth
  transactionQueryParams.yearMonth = toYearMonth(yearMonth.value)
  if (oldYearMonth !== transactionQueryParams.yearMonth) {
    Object.assign(listInfo, Array.from({ length: 3 }, () => ({ ...initState })))
    walletInfo.transactionRecordVO.length = 0
    incomeRecord.length = 0
    expenditureRecord.length = 0
    changeList()
  }
}

const loadmore = async () => {
  if (listInfo[current.value + 1].state !== 'finished') {
    if (current.value === -1) delete transactionQueryParams.transactionType
    else transactionQueryParams.transactionType = current.value
    const res = await getTransactionRecordByPageAPI({
      ...transactionQueryParams,
      page: ++listInfo[current.value + 1].page
    })
    if (res.code === 200) {
      if (res.data.length < transactionQueryParams.pageSize) listInfo[current.value + 1].state = 'finished'
      if (current.value === -1) walletInfo.transactionRecordVO.push(...res.data)
      else if (current.value === 0) incomeRecord.push(...res.data)
      else expenditureRecord.push(...res.data)
    }
    else {
      listInfo[current.value + 1].state = 'error'
      listInfo[current.value + 1].page--
    }
  }
}

onReachBottom(() => {
  if (listInfo[current.value + 1].state === 'loading') loadmore()
})
</script>

<template>
  <scroll-view>
    <view class="head">
      <view class="money">
        <view style="margin-bottom: 10rpx; display: flex;">
          <view style="color: #dcdcdc; font-size: 26rpx;">总余额(元)</view>
          <image @click="show = !show" style="width: 36rpx; height: 36rpx; margin-left: 20rpx;" src="@/static/images/show.png" />
        </view>
        <wd-text v-if="show" custom-style="color: #fff; font-size: 54rpx;" mode="price" :text="walletInfo.balance" />
        <wd-text v-else custom-style="color: #fff; font-size: 54rpx;" :text="hideStr" />
        <view style="display: flex; color: #dcdcdc; font-size: 26rpx; margin-top: 44rpx;">
          <view>
            今日收入&nbsp;&nbsp;
            <wd-text v-if="show" custom-style="color: #fff;" mode="price" prefix="+" :text="walletInfo.todayIncome" />
            <wd-text v-else custom-style="color: #fff;" :text="hideStr" />
          </view>
          <view style="position: absolute; left: 50%;">
            今日支出&nbsp;&nbsp;
            <wd-text v-if="show" custom-style="color: #fff;" mode="price" prefix="−" :text="walletInfo.todayExpenditure" />
            <wd-text v-else custom-style="color: #fff;" :text="hideStr" />
          </view>
        </view>
      </view>
      <view class="operate">
        <navigator class="navigator" url="./rechargeOrWithdrawal?transactionType=0">
          <wd-button custom-style="width: 100%;" type="info" size="large">充值</wd-button>
        </navigator>
        <navigator class="navigator" :url="'./rechargeOrWithdrawal?transactionType=1&balance=' + walletInfo.balance">
          <wd-button custom-style="width: 100%;" size="large">提现</wd-button>
        </navigator>
      </view>
    </view>
    <view class="content">
      <view style="display: flex; justify-content: space-between">
        <view style="margin-top: 20rpx; margin-left: 30rpx;">选择年月</view>
        <wd-datetime-picker @confirm="changeDate" type="year-month" v-model="yearMonth" :max-date="new Date().getTime()" />
      </view>
      <wd-segmented @change="changeList" :options="list" v-model:value="current">
        <template #label="{ option }">
          <view>{{ option.payload }}</view>
        </template>
      </wd-segmented>
      <view class="list">
        <view v-if="current === -1">
          <view v-if="walletInfo.transactionRecordVO.length > 0">
            <view v-for="item in walletInfo.transactionRecordVO" class="item">
              <view class="item-left">
                <view class="item-name">{{ item.description }}</view>
                <view class="item-date">{{ item.transactionTime }}</view>
              </view>
              <wd-text mode="price" custom-class="custom-class" :prefix="item.transactionType === TransactionType.INCOME ? '+' : '−'" :text="item.amount" />
            </view>
            <wd-loadmore @reload="loadmore" :state="listInfo[0].state" finished-text="没有更多了" />
          </view>
          <wd-status-tip v-else image-size="400rpx" image="content" tip="暂无记录" />
        </view>
        <view v-else-if="current === 0">
          <view v-if="incomeRecord.length > 0">
            <view v-for="item in incomeRecord" class="item">
              <view class="item-left">
                <view class="item-name">{{ item.description }}</view>
                <view class="item-date">{{ item.transactionTime }}</view>
              </view>
              <wd-text mode="price" custom-class="custom-class" :prefix="item.transactionType === TransactionType.INCOME ? '+' : '−'" :text="item.amount" />
            </view>
            <wd-loadmore @reload="loadmore" :state="listInfo[1].state" finished-text="没有更多了" />
          </view>
          <wd-status-tip v-else image-size="400rpx" image="content" tip="暂无记录" />
        </view>
        <view v-else>
          <view v-if="expenditureRecord.length > 0">
            <view v-for="item in expenditureRecord" class="item">
              <view class="item-left">
                <view class="item-name">{{ item.description }}</view>
                <view class="item-date">{{ item.transactionTime }}</view>
              </view>
              <wd-text mode="price" custom-class="custom-class" :prefix="item.transactionType === TransactionType.INCOME ? '+' : '−'" :text="item.amount" />
            </view>
            <wd-loadmore @reload="loadmore" :state="listInfo[2].state" finished-text="没有更多了" />
          </view>
          <wd-status-tip v-else image-size="400rpx" image="content" tip="暂无记录" />
        </view>
      </view> 
    </view>
  </scroll-view>
</template>

<style scoped lang="scss">
.head {
  height: 400rpx;
  padding-top: 40rpx;
  background-color: var(--front-color);
  .money {
    width: 80%;
    height: 210rpx;
    margin: auto;
    padding: 20rpx 5%;
    border-radius: 20rpx;
    background: linear-gradient(90deg, #2796f2 0%, #4D80F0 100%);
    box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.4);
  }
  .operate {
    width: 90%;
    height: 150rpx;
    margin: auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .navigator {
      width: 48%;
      height: 90rpx;
      border-radius: 50rpx;
    }
  }
}
.content {
  padding: 0 5%;
  margin-top: 20rpx;
  background-color: var(--front-color);
  min-height: 740rpx;
  :deep(.theme) {
    background-color: var(--front-color);
    color: var(--color);
  }
  .list {
    background-color: var(--front-color2);
    min-height: 586rpx;
    .item {
      display: flex;
      justify-content: space-between;
      padding: 20rpx;
      align-items: center;
      .item-date {
        font-size: 24rpx;
      }
      :deep(.custom-class) {
        color: var(--color);
      }
    }
  }
}
</style>